package com.atguigu.gulimall.order.listener;

import com.atguigu.gulimall.order.biz.OrderBizService;
import com.atguigu.gulimall.util.consts.MqConst;
import com.atguigu.gulimall.util.service.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author nicc
 * @version 1.0
 * @className PayedOrderLintener
 * @date 2022-10-26 04:03
 */
@Slf4j
@Service
public class PayedOrderListener {

    @Autowired
    RabbitService rabbitService;

    @Autowired
    OrderBizService orderBizService;

    @RabbitListener(queues = MqConst.ORDER_PAYED_QUEUE)
    public void payedListener(Message message, Channel channel) throws IOException {
        log.info("订单服务监听到支付成功的订单消息");
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String json = new String(message.getBody());
        try {
            // 订单改为已支付；如果正好临界支付成功，消息在两个队列都有：关单队列、支付成功队列
            //1、【正常】支付成功队列消息先被消费、关单后消费。   订单状态会改为已支付，关单发现不是未支付就不关闭
            //2、关单队列消息先被消费，支付成功队列后消费。  订单状态先被改为已关闭，要求支付状态修改【未支付、已关闭】

            //期望如果是未支付或已关闭 都应该能修改成已支付【解决临界问题】
            orderBizService.updateOrderStatusPayed(json);

            channel.basicAck(deliveryTag,false);
        }catch (Exception e){

            //重试5次
            rabbitService.retry(channel,deliveryTag,json,5);
        }
    }
}
